package cn.virens.web.components.shiro.simple.ajax;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.cors.CorsUtils;

import cn.virens.web.components.shiro.comm.AjaxUtil;
import cn.virens.web.components.shiro.simple.simple.SimpleUserFilter;

public class AjaxUserFilter extends SimpleUserFilter {
	private Logger logger = LoggerFactory.getLogger(AjaxUserFilter.class);

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		return CorsUtils.isPreFlightRequest((HttpServletRequest) request) || super.preHandle(request, response);
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
		logger.debug(((HttpServletRequest) request).getRequestURI());

		// 获取认证令牌
		Subject subject = getSubject(request, response);
		if (subject == null) return response(request, response);

		// 获取当前登陆用户 & 获取当前用户的session
		Object principal = subject.getPrincipal();
		Session session = subject.getSession(false);
		if (principal == null || session == null) {
			return response(request, response);
		} else {
			checkSession(session, principal);
		}

		return true;
	}

	private static boolean response(ServletRequest request, ServletResponse response) {
		return AjaxUtil.write(request, response, AjaxUtil.failed("NoLogin", "请登录"));
	}
}
